package nioTest;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

public class NioSocketServer {
    public static void main(String[] args) throws IOException, InterruptedException {
        Selector serverSelector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.socket().bind(new InetSocketAddress(8080));
        serverSocketChannel.register(serverSelector, SelectionKey.OP_ACCEPT);
        Thread acceptThread = new Thread(() -> {
            while (true) {
                try {
                    if (serverSelector.select(1) > 0) {
                        Set<SelectionKey> selectionKeys = serverSelector.selectedKeys();
                        Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
                        while (keyIterator.hasNext()) {
                            SelectionKey next = keyIterator.next();
                            if (next.isAcceptable()) {
                                SocketChannel clientChanel = ((ServerSocketChannel) next.channel()).accept();
                                clientChanel.configureBlocking(false);
                                clientChanel.register(serverSelector, SelectionKey.OP_READ);
                                keyIterator.remove();
                            }
                            if (next.isReadable()) {
                                try {
                                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                                    SocketChannel socketChannel = (SocketChannel) next.channel();
                                    socketChannel.read(byteBuffer);
                                    byteBuffer.flip();
                                    socketChannel.register(serverSelector, SelectionKey.OP_WRITE, Charset.defaultCharset().newDecoder().decode(byteBuffer)
                                            .toString());
                                    keyIterator.remove();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            if (next.isWritable()) {
                                try {
                                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                                    String readString = (String) next.attachment();
                                    System.out.println(readString);
                                    byteBuffer.put(("get message:" + readString).getBytes());
                                    byteBuffer.flip();
                                    SocketChannel clientChannel = (SocketChannel) next.channel();
                                    clientChannel.write(byteBuffer);
                                    clientChannel.shutdownOutput();
                                    next.cancel();
                                    keyIterator.remove();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        acceptThread.start();
        acceptThread.join();
    }
}
